package cn.com.cifi.mars.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.cifi.mars.bean.dto.SysPositionOrgDataPermissionDto;
import cn.com.cifi.mars.bean.vo.sys.req.SaveSysPositionOrgDataPermissionReqParam;
import cn.com.cifi.mars.constant.HrOrgTypeEunm;
import cn.com.cifi.mars.entity.common.SysPositionOrgDataPermission;
import cn.com.cifi.mars.mapper.mars.SysPositionOrgDataPermissionMapper;
import cn.com.cifi.mars.service.SysPositionOrgDataPermissionService;
import cn.com.cifi.mars.util.UUIDUtils;

/**
 * <p>
 * 岗位组织机构数据权限表 服务实现类
 * </p>
 *
 * @author yyd
 * @since 2019-09-20
 */
@Service
public class SysPositionOrgDataPermissionServiceImpl extends ServiceImpl<SysPositionOrgDataPermissionMapper, SysPositionOrgDataPermission> implements SysPositionOrgDataPermissionService {

	@Autowired
	private SysPositionOrgDataPermissionMapper sysPositionOrgDataPermissionMapper;
	/**
	 * 添加岗位数据权限
	 */
	@Transactional
	@Override
	public int add(SaveSysPositionOrgDataPermissionReqParam param) {
		// 添加关联关系
		int num = 0;
		for (String positionId : param.getPositionIds()) {
			// 先删除岗位组织机构关联数据
			sysPositionOrgDataPermissionMapper.deletePositionId(positionId);
			for (String orgid : param.getOrgIds()) {
				SysPositionOrgDataPermission bean = new SysPositionOrgDataPermission();
				bean.setOrgid(orgid);
				bean.setPositionId(positionId);
				bean.setId(UUIDUtils.create());
				num = sysPositionOrgDataPermissionMapper.insert(bean);
			}
		}
		return num;
	}

	/**
	 * 显示岗位数据权限
	 */
	@Override
	public JSONArray querySysPositionOrgDataPermissionTree(String positionId) {
		List<SysPositionOrgDataPermissionDto> list=sysPositionOrgDataPermissionMapper.selectSysPositionOrgDataPermissionTree(positionId,HrOrgTypeEunm.ORG_32.getKey());
		
		List<SysPositionOrgDataPermissionDto> listTree=buildTree(list,"00000000");
		JSONArray trssJson= JSONArray.parseArray(JSON.toJSONString(listTree));
		return trssJson;
	}
	
	/**
	 * 递归子节点
	 * @param list
	 * @param parentId
	 * @return
	 */
	public static List<SysPositionOrgDataPermissionDto> buildTree(List<SysPositionOrgDataPermissionDto> list,String parentId){
		List<SysPositionOrgDataPermissionDto> menus=new ArrayList<>();
	    for (SysPositionOrgDataPermissionDto menu : list) {  
	    	  //本身id
	          String menuId = menu.getOrgdepid();
	          //父id
	          String pid = menu.getParentOrgid();
	          if (parentId.equals(pid)) {  
	              List<SysPositionOrgDataPermissionDto> menuLists = buildTree(list, menuId);  
	              menu.setChildMenu(menuLists);
	              menus.add(menu);  
	          }  
	    }  
		return menus;
	}
	
	
}
